#include "clientsocket.h"

ClientSocket::ClientSocket(QObject *parent)
: QTcpSocket(parent)
{
	blockSize = 0;
	clientInfo.clientSocket = this;
	connect(this, SIGNAL(readyRead()),
		this, SLOT(receiveMessage()));
	connect(this, SIGNAL(disconnected()),
		this, SLOT(deleteScoket()));
}

ClientSocket::~ClientSocket()
{

}

void ClientSocket::receiveMessage()
{
	QDataStream in(this);
	in.setVersion(QDataStream::Qt_4_0);

	if (blockSize == 0)
	{
		if (bytesAvailable() < (int)sizeof(quint16))
			return;
		in >> blockSize;
	}
	if (bytesAvailable() < blockSize)
    {
        return;
    }

	in >> clientInfo.requestKind;

    switch (clientInfo.requestKind)
    {
    case LOGIN:
        in >> clientInfo.account >> clientInfo.passWord;
        break;
    case LOGOUT:
        in >> clientInfo.account;
        break;
    case TALK:
        in >> clientInfo.message;
        break;
    case GET_USER_INFORMATION:
        in >> clientInfo.account;
        break;
    case CHANGE_INFORMATION:
        in >> clientInfo.userInfo;
        break;
    case CODE_SHARE:
        in >> clientInfo.message;
        break;
    case ADD_INFORMATION:
        in >> clientInfo.message;
        break;
    default:
        break;
    }

	blockSize = 0;
	emit sendSignal(clientInfo);
}

void ClientSocket::sendMessage(const ClientInfo &info, const QVector<UserInformation> &userInfoVec)
{
	QByteArray block;
	QDataStream out(&block, QIODevice::WriteOnly);
	out.setVersion(QDataStream::Qt_4_0);
	out << (qint16)0;
	out << info.replyKind;

    switch (info.replyKind)
    {
    case GET_USER_INF_SUCCESS:
		out << info.userInfo;
        break;
    case TALK:
		out << info.message;
        break;
    case GET_ALL_SUCCESS:
        out << userInfoVec;
        break;
    case CODE_UPDATE:
        out << info.message;
        break;
    case INFO_UPDATE:
        out << info.message;
        break;
    default:
        break;
    }

	out.device()->seek(0);
	out << (qint16)(block.size() - sizeof(qint16));

	write(block);
}

void ClientSocket::deleteScoket()
{
	if(!clientInfo.account.isEmpty())
		emit deleteSignal(clientInfo.account);
	deleteLater();
}